package com.hot100.mid;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 电话号码的字母组合
 * @date 2022/8/5 14:33
 */
public class Demo06 {



    //设置全局列表存储最后的结果
    static List<String> list = new ArrayList<>();
    //每次迭代获取一个字符串，所以会设计大量的字符串拼接，所以这里选择更为高效的 StringBuild
    static StringBuilder  temp = new StringBuilder();

    public static void main(String[] args) {
        List<String> strings = letterCombinations("23");
        System.out.println(strings);
    }

    public static List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {
            return list;
        }
        //初始对应所有的数字，为了直接对应2-9，新增了两个无效的字符串""
        String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        //迭代处理
       // backTracking(digits, numString, 0);
        StringBuilder newStr= new StringBuilder();
        backTracking1(numString,digits,0,newStr);
        return list;

    }

    //比如digits如果为"23",num 为0，则str表示2对应的 abc
    public  static void backTracking(String digits, String[] numString, int num) {
        //遍历全部一次记录一次得到的字符串
        if (num == digits.length()) {
            list.add(temp.toString());
            return;
        }
        //str 表示当前num对应的字符串
        String str = numString[digits.charAt(num) - '0'];
        for (int i = 0; i < str.length(); i++) {
            temp.append(str.charAt(i));
            //c
            backTracking(digits, numString, num + 1);
            //剔除末尾的继续尝试
            temp.deleteCharAt(temp.length() - 1);
        }
    }


    public static void  backTracking1(String[] strs,String digits, int n,StringBuilder baseStr ){

        if(Objects.equals(digits, "")){
            return ;
        }
        if(digits.length()==n){
            list.add(baseStr.toString());
            return;
        }
        String str=strs[digits.charAt(n)-'0'];
        for(int i=0;i<str.length();i++){
            String newString= String.valueOf(str.charAt(i));
            StringBuilder newStr= new StringBuilder(baseStr + newString);
            backTracking1( strs, digits, n+1,newStr);
            newStr.deleteCharAt(newStr.length()-1);

        }
    }
}
